import org.jrtaudio.*;

public class RecordAndPlay
{
	static final int SAMPLES = 44100*3*2; // 3 seconds of recording (both channels)
	boolean listening = true;
	
	float data[];
	int pointer;
	
	public RecordAndPlay()
	{
		data = new float[SAMPLES];
		pointer = 0;
	}
	
	public void startPlayback()
	{
		pointer = 0;
		listening = false;
	}
	
	static public void main(String args[]) throws InterruptedException
	{
		RecordAndPlay rap = new RecordAndPlay();
		
		JRtAudio au = new JRtAudio();
		au.showWarnings();
		int out = au.getDefaultOutputDevice();
		int in = au.getDefaultInputDevice();	
		
		// Setup recording
		System.out.println("Opening an input stream...");				
		DeviceInfo devin = au.getDeviceInfo(in);
		StreamParameters inParams = new StreamParameters();
		inParams.nChannels = devin.inputChannels;
		inParams.deviceId = in;
		
		int nf = au.openStream(null,inParams,44100,512,rap);
		au.startStream();	
		System.out.println("Recording...");
		Thread.sleep(2000);
		au.stopStream();
		au.closeStream();
		
		// Setup playback
		rap.startPlayback();
		
		au = new JRtAudio();
		DeviceInfo devout = au.getDeviceInfo(out);
		StreamParameters oParams = new StreamParameters();
		oParams.nChannels = devout.outputChannels;
		oParams.deviceId = out;
		au.openStream(oParams,null,44100,512,rap);
		
		au.startStream();
		System.out.println("Playing...");
		Thread.sleep(4000);
		au.stopStream();
		System.exit(0);
	}	
	
	public int callback(float[] outputBuffer, float[] inputBuffer, int nBufferFrames, double streamTime, int status)
	{
		if (listening)
		{
			if (pointer > data.length-2*nBufferFrames)
			{
				// don't do anything
			}
			else
			{
				// record at 
				System.arraycopy(inputBuffer,0,data,pointer,nBufferFrames*2);
				pointer += 2*nBufferFrames;
			}
		}
		else
		{
			if (pointer > data.length-2*nBufferFrames)
			{
				// wrap around
				pointer = 0;
			}
			
			// playback 			
			System.arraycopy(data,pointer,outputBuffer,0,2*nBufferFrames);
			pointer += 2*nBufferFrames;
		}
		return 0;
	}
	
	
}